package com.css.fxfzdzzh.modules.eqLandslide.lawAnalysis.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzdzzh.base.attachment.entity.AttachmentInfoEntity;
import com.css.fxfzdzzh.base.attachment.service.AttachmentInfoService;
import com.css.fxfzdzzh.base.response.RestResponse;
import com.css.fxfzdzzh.modules.basicData.entity.PageResult;
import com.css.fxfzdzzh.modules.basicData.entity.SysDataVersion;
import com.css.fxfzdzzh.modules.basicData.landslideSite.service.LandslideSiteService;
import com.css.fxfzdzzh.modules.basicData.param.sysDataVersion.SysDataVersionPageParam;
import com.css.fxfzdzzh.modules.basicData.repository.impl.SysDataVersionRepository;
import com.css.fxfzdzzh.modules.basicData.service.impl.LithologyService;
import com.css.fxfzdzzh.modules.basicData.service.impl.SensingImageService;
import com.css.fxfzdzzh.modules.basicData.service.impl.SysDataVersionService;
import com.css.fxfzdzzh.modules.basicData.vo.sysDataVersion.SysDataVersionPageVo;
import com.css.fxfzdzzh.modules.drill.service.DrillService;
import com.css.fxfzdzzh.modules.eqLandslide.count.service.impl.EqLandslideServiceImpl;
import com.css.fxfzdzzh.modules.eqLandslide.lawAnalysis.entity.*;
import com.css.fxfzdzzh.modules.eqLandslide.lawAnalysis.param.CountParam;
import com.css.fxfzdzzh.modules.eqLandslide.lawAnalysis.repository.LawAnalysisRepository;
import com.css.fxfzdzzh.modules.eqLandslide.lawAnalysis.service.LawAnalysisService;
import com.css.fxfzdzzh.modules.eqLandslide.lawAnalysis.vo.BufferAreaVO;
import com.css.fxfzdzzh.modules.eqLandslide.lawAnalysis.vo.SlopesVO;
import com.css.fxfzdzzh.modules.evaluate.VO.VersionPageVO;
import com.css.fxfzdzzh.modules.hypergraph.service.HypergraphService;
import com.css.fxfzdzzh.modules.tifData.service.ElevationMapService;
import com.css.fxfzdzzh.util.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: fxfzdzzh
 * @Author: lhl
 * @CreateDate: 2023/2/27 14:56
 */
@Service
public class LawAnalysisServiceImpl implements LawAnalysisService {

    @Resource
    LawAnalysisRepository lawAnalysisRepository;
    @Resource
    DrillService drillService;
    @Resource
    LandslideSiteService landslideSiteService;
    @Resource
    SysDataVersionService sysDataVersionService;
    @Resource
    SensingImageService sensingImageService;
    @Resource
    EqLandslideServiceImpl eqLandslideService;
    @Resource
    ElevationMapService elevationMapService;
    @Resource
    LithologyService lithologyService;
    @Resource
    SysDataVersionRepository sysDataVersionRepository;
    @Resource
    AttachmentInfoService attachmentInfoService;
    @Resource
    HypergraphService hypergraphService;

    @Value("${basicData.url}")
    public String basicDataUrl;


    @Override
    public RestResponse count1(CountParam param1) {
        delete(1);
        String url;
        JSONArray jsonArray = null;
        if ("1".equals(param1.getTab1())) {
            JSONObject valueMap = new JSONObject();
            valueMap.put("versionCode", param1.getParam1());
            valueMap.put("geom", param1.getGeomText());
            url = basicDataUrl + "/datacenter/sysDataVersion/queryAllByVersionCode";
            jsonArray = (JSONArray) drillService.getJCSJ(url, 5, valueMap).getData();
        } else if ("2".equals(param1.getTab1())) {
            url = basicDataUrl + "/datacenter/jcEarthquakeDamageSurveyIsoline/findAll?jcedsId=" + param1.getParam1();
            jsonArray = (JSONArray) drillService.getJCSJ(url, 3).getData();
        }
        if (jsonArray == null) {
            return RestResponse.fail("该区域没有" + param1.getParam1() + "的等震线数据");
        }

        List<SlopesVO> slopes1 = new ArrayList<>();
        if (PlatformObjectUtils.isNotEmpty(param1.getParam2())) {
            slopes1 = landslideSiteService.getSlopeAreaByGeomAndVersion1(param1.getGeomText(), param1.getParam2());
        }
        if (PlatformObjectUtils.isNotEmpty(param1.getParam3())) {
            if (slopes1 != null) {
                slopes1.addAll(sensingImageService.getSlopeAreaByGeomAndVersion1(param1.getGeomText(), param1.getParam3()));
            } else {
                slopes1 = sensingImageService.getSlopeAreaByGeomAndVersion1(param1.getGeomText(), param1.getParam3());
            }
        }
        Map<String, JSONArray> map1 = new HashMap<>();
        JSONArray jsonArray1 = null;
        JSONObject jsonObject1 = null;
        String intensity1;//烈度
        for (int j = 0; j < jsonArray.size(); j++) {
            jsonObject1 = jsonArray.getJSONObject(j);
            intensity1 = jsonObject1.getString("intensity");
            if (map1.containsKey(intensity1)) {
                jsonArray1 = map1.get(intensity1);
            } else {
                jsonArray1 = new JSONArray();
            }
            jsonArray1.add(jsonObject1);
            map1.put(intensity1, jsonArray1);
        }
        DzzhSlideParam dzzhSlideParam = saveDzzhSlideParam(param1, "1");
        //V、VI、VII、VIII、IX、X、XI、XII
        for (int key = 5; key < 13; key++) {
            String intensity = "";//烈度
            switch (key) {
                case 5:
                    intensity = "Ⅴ";
                    break;
                case 6:
                    intensity = "Ⅵ";
                    break;
                case 7:
                    intensity = "Ⅶ";
                    break;
                case 8:
                    intensity = "Ⅷ";
                    break;
                case 9:
                    intensity = "Ⅸ";
                    break;
                case 10:
                    intensity = "Ⅹ";
                    break;
                case 11:
                    intensity = "Ⅺ";
                    break;
                case 12:
                    intensity = "Ⅻ";
                    break;
            }
            Object[] objects1 = null;
            if (map1.get(intensity) != null) {
                objects1 = getObjects(slopes1, map1.get(intensity));
            } else {
                continue;
            }

            DzzhSlideResultIntensity teraData = new DzzhSlideResultIntensity();
            teraData.setDsriId(UUIDGenerator.getUUID());
            teraData.setIntensity(intensity);
            if (PlatformObjectUtils.isNotEmpty(objects1)) {
                teraData.setSlopeArea(new BigDecimal(objects1[2]+"").divide(BigDecimal.valueOf(1000000), 4, BigDecimal.ROUND_UP));
                BigDecimal slopeDensity=objects1[1] == null || new BigDecimal(objects1[1].toString()).compareTo(BigDecimal.ZERO)==0? BigDecimal.ZERO : (new BigDecimal(objects1[2]+"")
                        .divide(new BigDecimal(objects1[1]+""), 4, BigDecimal.ROUND_UP));
                if (slopeDensity.compareTo(BigDecimal.ONE)>0){
                    slopeDensity=BigDecimal.ONE;
                }
                teraData.setSlopeDensity(slopeDensity);
                teraData.setGeomText((String) objects1[0]);
            }
            teraData.setDspId(dzzhSlideParam.getId());
            // teraData.setIntensityVersion(param1.getParam1());
            // teraData.setLandsSiteVersion(param1.getParam2());
            // teraData.setSensingImgVersion(param1.getParam3());
            // teraData.setIntensitySource(param1.getTab1());
            lawAnalysisRepository.save1(teraData);
        }

        return RestResponse.succeed("计算成功!");
    }

    /**
     * 获取分布规律分析计算与基础数据关联的数据版本信息
     *
     * @param tab
     * @return
     */
    @Override
    public RestResponse getParam1Version(String tab, VersionPageVO vo) {
        vo.setTypeCode(null);
        String url = basicDataUrl + "/datacenter/sysDataVersion/page?hasNationwide=1";
        Map<String, Object> map = JSONObject.parseObject(JSONObject.toJSONString(vo), Map.class);
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (entry.getValue() != null) {
                url = url + "&" + entry.getKey() + "=" + entry.getValue();
            }
        }
        if (PlatformObjectUtils.isNotEmpty(vo.getProvince())) {
            url = url + "&dataRangeProvince = " + vo.getProvince();
        } else {
            url = url + "&dataRangeProvince = -1";

        }
        RestResponse jcsjPage = null;
        switch (tab) {
            case "1"://断层
                url = url + "&typeCode=dc";
                jcsjPage = drillService.getJCSJ(url, 2);
                break;
            case "2"://高程
                url = url + "&typeCode=demgcsj";
                jcsjPage = drillService.getJCSJ(url, 2);
                break;
            case "3"://地层岩性
                url = url + "&typeCode=dcyx1";
                jcsjPage = drillService.getJCSJ(url, 2);
                break;
            case "4"://道路
                url = url + "&typeCode=dl1";
                jcsjPage = drillService.getJCSJ(url, 2);
                break;
            case "5"://地震动峰值加速度数据（50年超越概率2%）
                url = url + "&typeCode=pga002";
                jcsjPage = drillService.getJCSJ(url, 2);
                break;
            case "6"://地震动峰值加速度数据（50年超越概率10%）
                url = url + "&typeCode=pga010";
                jcsjPage = drillService.getJCSJ(url, 2);
                break;
            case "7"://地震动峰值加速度数据（50年超越概率63%）
                url = url + "&typeCode=pga063";
                jcsjPage = drillService.getJCSJ(url, 2);
                break;
            case "8"://中国地震综合等震线
                url = url + "&typeCode=dzzhdzx1";
                jcsjPage = drillService.getJCSJ(url, 2);
                break;
        }
        return jcsjPage;
    }

    @Override
    public RestResponse getParam2Version(VersionPageVO param) {
        Map<String, Object> map = landslideSiteService.pageForAnalyse(param);

        return RestResponse.succeed(map);
    }

    /**
     * 滑坡遥感影像解译数据
     *
     * @param param
     * @return
     */
    @Override
    public RestResponse getParam3Version(VersionPageVO param) {
        SysDataVersionPageParam pageParam = new SysDataVersionPageParam();
        if (PlatformObjectUtils.isNotEmpty(param.getProvince())) {
//            pageParam.setProvince(param.getProvince());
            pageParam.setDataRangeProvince(param.getProvince());
        } else {
//            pageParam.setProvince("-1");
        }
        if (PlatformObjectUtils.isNotEmpty(param.getVersionDesc())) {
            pageParam.setVersionDesc(param.getVersionDesc());
        }
        if (PlatformObjectUtils.isNotEmpty(param.getUploadUser())) {
            pageParam.setUploadUsername(param.getUploadUser());
        }
        if (PlatformObjectUtils.isNotEmpty(param.getUploadStartTime())) {
            pageParam.setUploadStartTime(param.getUploadStartTime());
        }
        if (PlatformObjectUtils.isNotEmpty(param.getUploadEndTime())) {
            pageParam.setUploadEndTime(param.getUploadEndTime());
        }
        pageParam.setHasNationwide(1);
        pageParam.setDataType("hpygyx");
        PageResult<SysDataVersionPageVo> page = sysDataVersionService.page(pageParam);
        return RestResponse.succeed(page);
    }

    @Override
    public RestResponse count2(CountParam param1) {
        delete(2);
        //生成缓冲区（30公里）
        String bufferGeomText = lawAnalysisRepository.getBufferByGeomMeter(param1.getGeomText(), 30 * 1000);
        String url = basicDataUrl + "/datacenter/sysDataVersion/queryAllByVersionCode";
        JSONObject valueMap = new JSONObject();
        valueMap.put("versionCode", param1.getParam1());
        valueMap.put("geom", bufferGeomText);
        JSONObject jsonObject1 = (JSONObject) drillService.getJCSJ(url, 1, valueMap).getData();
        JSONArray jsonArray1 = jsonObject1.getJSONArray("data");
        if (jsonArray1 == null || jsonArray1.size() < 1) {
            return RestResponse.fail("该区域没有" + param1.getParam1() + "版本的断层数据");
        }
        DzzhSlideParam dzzhSlideParam = saveDzzhSlideParam(param1, "2");
        List<String> list = new ArrayList<>();
        //区域面积（度)
        BigDecimal areaDegree = lawAnalysisRepository.getAreaDegreeByGeom(param1.getGeomText());
        //区域总面积（平方公里)
//        BigDecimal areaTransform = lawAnalysisRepository.getAreaByGeom(param1.getGeomText());
        //根据区域投影到6度带或3度带，计算投影面积之和（平方公里)
        BigDecimal areaTransform = elevationMapService.getAreaByGeomEpsgCount(param1.getGeomText());
        //获取全部断层线空间数据
        JSONObject jsonObject = null;
        String geomText = "";//全部断层线空间数据
        for (int i = 0; i < jsonArray1.size(); i++) {
            jsonObject = jsonArray1.getJSONObject(i);
            String lineGeomText = jsonObject.getString("geom");
            if (PlatformObjectUtils.isNotEmpty(geomText)) {
                geomText = lawAnalysisRepository.getStUnion(geomText, lineGeomText);
            } else {
                geomText = lineGeomText;
            }
        }
        //7,>30;6,25~30;5,20~25;4,15~20;3,10~15;2,5~10;1,0~5
        for (int key = 1; key < 8; key++) {
            List<SlopesVO> slopes1 = null;
            //断层缓冲区的面积和空间数据
            /*BufferAreaVO objects = lawAnalysisRepository.getBufferByGeom(param1.getGeomText(), geomText,
                    key * 5000, (key - 1) * 5000);*/
            //区域的缓冲区内断层数据按距离分段生成缓冲区环
            BufferAreaVO objects = lawAnalysisRepository.getBufferByGeomBuffer(bufferGeomText, param1.getGeomText(), geomText,
                    key * 5000, (key - 1) * 5000);
            if (objects == null || objects.getGeom() == null || objects.getGeom().equals("POLYGON EMPTY")) {
                continue;
            }
            //计算滑坡面积
            BigDecimal slopeArea = BigDecimal.ZERO;
            if (PlatformObjectUtils.isNotEmpty(param1.getParam2())) {
                slopes1 = landslideSiteService.getSlopeAreaByGeomAndVersion1(objects.getGeom(), param1.getParam2());
            }
            if (PlatformObjectUtils.isNotEmpty(param1.getParam3())) {
                if (slopes1 != null) {
                    slopes1.addAll(sensingImageService.getSlopeAreaByGeomAndVersion1(objects.getGeom(), param1.getParam3()));
                } else {
                    slopes1 = sensingImageService.getSlopeAreaByGeomAndVersion1(objects.getGeom(), param1.getParam3());
                }
            }
            if (slopes1 != null) {
                for (SlopesVO fileData : slopes1) {
                    if (!list.contains((String) fileData.getId())) {
                        list.add((String) fileData.getId());
                        slopeArea = slopeArea.add((BigDecimal) fileData.getLandslideArea());
                    }
                }
                slopes1.clear();
            }

            //根据面积（度）与区域总面积（度）的比例和区域投影总面积（平方公里）获取投影面积
            BigDecimal area = objects.getArea().divide(areaDegree, 6, BigDecimal.ROUND_HALF_UP).multiply(areaTransform);
            objects.setArea(area);
            Object[] objects2 = new Object[3];
            objects2[0] = objects.getGeom();//与区域相交部分的空间数据
            objects2[1] = objects.getArea();//面积（平方公里）
            objects2[2] = slopeArea;//滑坡面积（平方公里）

            DzzhSlideResultFault faultData = new DzzhSlideResultFault();
            faultData.setDsrfId(UUIDGenerator.getUUID());
            faultData.setFaultRange(String.valueOf(key));
            if (PlatformObjectUtils.isNotEmpty(objects2)) {
                faultData.setSlopeArea(new BigDecimal(objects2[2]+"").divide(BigDecimal.valueOf(1000000), 4, BigDecimal.ROUND_UP));
                BigDecimal slopeDensity=objects2[1] == null || new BigDecimal(objects2[1].toString()).compareTo(BigDecimal.ZERO)==0? BigDecimal.ZERO : (new BigDecimal(objects2[2]+"")
                        .divide(new BigDecimal(objects2[1]+""), 4, BigDecimal.ROUND_UP));
                if (slopeDensity.compareTo(BigDecimal.ONE)>0){
                    slopeDensity=BigDecimal.ONE;
                }
                faultData.setSlopeDensity(slopeDensity);
                faultData.setGeomText((String) objects2[0]);
            }
            faultData.setDspId(dzzhSlideParam.getId());
            // param1.getGeomText();
            // faultData.setFaultVersion(param1.getParam1());
            // faultData.setLandsSiteVersion(param1.getParam2());
            // faultData.setSensingImgVersion(param1.getParam3());
            lawAnalysisRepository.save2(faultData);
        }

        return RestResponse.succeed("计算成功！");
    }

    /*@Override
    public RestResponse count2(CountParam param1) {
        delete(2);

        String url = basicDataUrl + "/datacenter/sysDataVersion/queryAllByVersionCode";
        JSONObject valueMap = new JSONObject();
        valueMap.put("versionCode", param1.getParam1());
        valueMap.put("geom", param1.getGeomText());
        JSONObject jsonObject1 = (JSONObject) drillService.getJCSJ(url, 1, valueMap).getData();
        JSONArray jsonArray1 = jsonObject1.getJSONArray("data");
        if (jsonArray1 == null || jsonArray1.size() < 1) {
            return RestResponse.fail("该区域没有" + param1.getParam1() + "版本的断层数据");
        }
        DzzhSlideParam dzzhSlideParam = saveDzzhSlideParam(param1, "2");
        List<String> list = new ArrayList<>();
        Map<Integer, Object[]> map = new HashMap<>();
        //7,>30;6,25~30;5,20~25;4,15~20;3,10~15;2,5~10;1,0~5
        for (int key = 1; key < 8; key++) {
            JSONObject jsonObject = null;
            // String geomText = null;//水系与区域相交部分的空间数据
            // BigDecimal areaByGeom = BigDecimal.ZERO;//水系的面积

            List<SlopesVO> slopes1 = null;
            for (int i = 0; i < jsonArray1.size(); i++) {
                jsonObject = jsonArray1.getJSONObject(i);
                String geomText = jsonObject.getString("geom");

                BigDecimal slopeArea = BigDecimal.ZERO;
                if (PlatformObjectUtils.isNotEmpty(param1.getParam2())) {
                    slopes1 = landslideSiteService.getSlopeAreaByGeomAndVersion1(param1.getGeomText(), geomText,
                            key * 5000,(key - 1) * 5000, param1.getParam2());
                }
                if (PlatformObjectUtils.isNotEmpty(param1.getParam3())) {
                    if (slopes1 != null) {
                        slopes1.addAll(sensingImageService.getSlopeAreaByGeomAndVersion1(param1.getGeomText(), geomText,
                                key * 5000, (key - 1) * 5000, param1.getParam3()));
                    } else {
                        slopes1 = sensingImageService.getSlopeAreaByGeomAndVersion1(param1.getGeomText(), geomText,
                                key * 5000,(key - 1) * 5000, param1.getParam3());
                    }
                }

                if (slopes1 != null) {
                    for (SlopesVO fileData : slopes1) {
                        if (!list.contains((String) fileData.getId())) {
                            list.add((String) fileData.getId());
                            slopeArea = slopeArea.add((BigDecimal) fileData.getLandslideArea());
                        }
                    }
                    //断层缓冲区的面积和空间数据
                    BufferAreaVO objects = lawAnalysisRepository.getBufferByGeom(param1.getGeomText(), geomText,
                            key * 5000,(key - 1) * 5000);
                    if (objects != null) {
                        Object[] objects2 = null;
                        if (map.containsKey(key)) {
                            objects2 = map.get(key);
                            objects2[0] = lawAnalysisRepository.getStUnion(objects.getGeom(), objects2[0]);
                            objects2[1] = ((BigDecimal) objects2[1]).add((BigDecimal) objects.getArea());
                            // objects2[2] = ((BigDecimal) objects2[2]).add(slopeArea);
                        } else {
                            objects2 = new Object[3];
                            objects2[0] = objects.getGeom();//与区域相交部分的空间数据
                            objects2[1] = objects.getArea();//面积
                            objects2[2] = slopeArea;//滑坡面积
                            map.put(key, objects2);
                        }
                    }
                    slopes1.clear();
                }
            }

            list.clear();
        }

        for (Integer key2 : map.keySet()) {
            Object[] objects1 = map.get(key2);
            DzzhSlideResultFault faultData = new DzzhSlideResultFault();
            faultData.setDsrfId(UUIDGenerator.getUUID());
            faultData.setFaultRange(String.valueOf(key2));
            if (PlatformObjectUtils.isNotEmpty(objects1)) {
                faultData.setSlopeArea((BigDecimal) objects1[2]);
                faultData.setSlopeDensity(objects1[1]==null?BigDecimal.ZERO:((BigDecimal) objects1[2])
                        .divide((BigDecimal) objects1[1], 1, BigDecimal.ROUND_UP));
                faultData.setGeomText((String) objects1[0]);
            }
            faultData.setDspId(dzzhSlideParam.getId());
            // param1.getGeomText();
            // faultData.setFaultVersion(param1.getParam1());
            // faultData.setLandsSiteVersion(param1.getParam2());
            // faultData.setSensingImgVersion(param1.getParam3());
            lawAnalysisRepository.save2(faultData);
        }
        return RestResponse.succeed("计算成功！");
    }*/

    @Override
    public RestResponse count3(CountParam param1) {
        delete(3);
        String url = basicDataUrl + "/jcTera/getFilePathByVersion?dataVersion=" + param1.getParam1();
        RestResponse jcsj = drillService.getJCSJ(url, 2);
        JSONObject jsonObject = (JSONObject) jcsj.getData();
        if (jsonObject == null || jsonObject.size() < 1) {
            return RestResponse.fail("该区域没有" + param1.getParam1() + "版本的高程数据");
        }
        Map<String, List<Map<String, String>>> listMap =
                elevationMapService.getElevationByGeomAndTIF(param1.getGeomText()
                        , jsonObject.getString("filePath"));

        List<SlopesVO> slopes1 = new ArrayList<>();
        if (PlatformObjectUtils.isNotEmpty(param1.getParam2())) {
            slopes1 = landslideSiteService.getSlopeAreaByGeomAndVersion1(param1.getGeomText(), param1.getParam2());
        }
        if (PlatformObjectUtils.isNotEmpty(param1.getParam3())) {
            if (slopes1 != null) {
                slopes1.addAll(sensingImageService.getSlopeAreaByGeomAndVersion1(param1.getGeomText(), param1.getParam3()));
            } else {
                slopes1 = sensingImageService.getSlopeAreaByGeomAndVersion1(param1.getGeomText(), param1.getParam3());
            }
        }
        DzzhSlideParam dzzhSlideParam = saveDzzhSlideParam(param1, "3");
        //1,<0.6;2,0.6~1;3,1~1.5;4,1.5~2;5,2~2.5;6,2.5~3;7,3~3.5;8,>3.5
        for (int key = 1; key < 9; key++) {
            Object[] objects1 = null;
            if (listMap.get(String.valueOf(key)) != null) {
                objects1 = getObjects(slopes1, JSON.parseArray(JSON.toJSONString(listMap.get(String.valueOf(key)))));
            } else {
                continue;
            }

            DzzhSlideResultTera teraData = new DzzhSlideResultTera();
            teraData.setDsrtId(UUIDGenerator.getUUID());
            teraData.setTeraRange(String.valueOf(key));
            if (PlatformObjectUtils.isNotEmpty(objects1)) {
                teraData.setSlopeArea(new BigDecimal(objects1[2]+"").divide(BigDecimal.valueOf(1000000), 4, BigDecimal.ROUND_UP));
                BigDecimal slopeDensity=objects1[1] == null || new BigDecimal(objects1[1].toString()).compareTo(BigDecimal.ZERO) ==0 ? BigDecimal.ZERO : (new BigDecimal(objects1[2]+"")
                        .divide(new BigDecimal(objects1[1]+""), 4, BigDecimal.ROUND_UP));
                if (slopeDensity.compareTo(BigDecimal.ONE)>0){
                    slopeDensity=BigDecimal.ONE;
                }
                teraData.setSlopeDensity(slopeDensity);
                teraData.setGeomText((String) objects1[0]);
            }
            teraData.setDspId(dzzhSlideParam.getId());
            // teraData.setTeraVersion(param1.getParam1());
            // teraData.setLandsSiteVersion(param1.getParam2());
            // teraData.setSensingImgVersion(param1.getParam3());
            lawAnalysisRepository.save3(teraData);
        }

        return RestResponse.succeed("计算成功!");
    }

    /**
     * 坡度
     * @param param1
     * @return
     */
    @Override
    public RestResponse count4(CountParam param1) {
        delete(4);
        String resultLayerName1 = this.getDataBySlopeVersion(param1.getGeomText(), param1.getParam1());
        if (PlatformObjectUtils.isEmpty(resultLayerName1)){
            return RestResponse.fail("任务范围内不包含"+param1.getParam1()+"版本的坡度文件数据！");
        }

        // 1,<15;2,15~25;3,25~35;4,35~45;5,45~55;6,>55
        String countString1 = "Con([dzzhTifCount." + resultLayerName1 + "]<0,-9999,Con([dzzhTifCount." + resultLayerName1 + "]<15,1," +
                "Con([dzzhTifCount." + resultLayerName1 + "]<25,2,Con([dzzhTifCount." + resultLayerName1 + "]<35,3," +
                "Con([dzzhTifCount." + resultLayerName1 + "]<45,4,Con([dzzhTifCount." + resultLayerName1 + "]<55,5,6))))))";
        String resultLayerName2 = "dzzh分布规律分析_坡度计算" + System.currentTimeMillis();//裁剪计算结果数据集
        RestResponse restResponse4 = countTif(countString1, resultLayerName2);
        if (restResponse4.getCode() != 200) {
            return restResponse4;
        }
        String resultLayerName3 = "dzzh_坡度_矢量化结果数据集" + System.currentTimeMillis();
        String resultLayerName4 = "dzzh_slide_slope_values"+BigDecimal.valueOf(Math.random()*1000000).intValue()+BigDecimal.valueOf(Math.random()*10000).intValue();
        Map<String, Object> map2_1 = new HashMap<>();
        map2_1.put("type", "gridFusion");
        map2_1.put("layerName", resultLayerName2);
        map2_1.put("resultLayerName1", resultLayerName3);
        map2_1.put("resultLayerName2", resultLayerName4);
        RestResponse serverToken = hypergraphService.getServerToken(map2_1);
        if (serverToken.getCode() != 200) {
            return serverToken;
        }

        List<Map<String, Object>> slopes1 = new ArrayList<>();
        if (PlatformObjectUtils.isNotEmpty(param1.getParam2())) {
            slopes1 = landslideSiteService.getByGeomAndVersion2(resultLayerName4, param1.getParam2());
        }
        if (PlatformObjectUtils.isNotEmpty(param1.getParam3())) {
            if (slopes1 != null) {
                slopes1.addAll(sensingImageService.getByGeomAndVersion2(resultLayerName4, param1.getParam3()));
            } else {
                slopes1 = sensingImageService.getByGeomAndVersion2(resultLayerName4, param1.getParam3());
            }
        }

        Map<Integer, Object[]> map1 = new HashMap<>();
        Object[] objects=null;
        for (Map<String, Object> slope:slopes1){
            Integer key=Double.valueOf(slope.get("gridvalue")+"").intValue();
            if (map1.containsKey(key)){
                objects=map1.get(key);
                objects[1] = new BigDecimal(objects[1]+"").add(new BigDecimal(slope.get("smarea")+""));
            }else {
                objects = new Object[3];
                objects[0] = slope.get("smgeometry");//坡度与区域相交部分的空间数据
                objects[1] = slope.get("smarea");//坡度的面积
                objects[2] = slope.get("sum");//滑坡面积
            }
            map1.put(key,objects);
        }
        DzzhSlideParam dzzhSlideParam = saveDzzhSlideParam(param1, "4");
        // 1,<15;2,15~25;3,25~35;4,35~45;5,45~55;6,>55
        List<Map<String, Object>> mapList = lawAnalysisRepository.getByTableName(resultLayerName4);
        for (Map<String, Object> entity :mapList) {
            //gridvalue,st_asText(smgeometry) smgeometry
            Integer key = Double.valueOf(entity.get("gridvalue")+"").intValue();
            Object[] objects1 = map1.get(key);
            DzzhSlideResultSlope teraData = new DzzhSlideResultSlope();
            teraData.setDsrsId(UUIDGenerator.getUUID());
            teraData.setSlopeRange(String.valueOf(key));
            if (PlatformObjectUtils.isNotEmpty(objects1)) {
                teraData.setSlopeArea(new BigDecimal(objects1[2]+"").divide(BigDecimal.valueOf(1000000), 4, BigDecimal.ROUND_UP));
                BigDecimal slopeDensity=objects1[1] == null || new BigDecimal(objects1[1].toString()).compareTo(BigDecimal.ZERO)==0? BigDecimal.ZERO : (new BigDecimal(objects1[2]+"")
                        .divide(new BigDecimal(objects1[1]+""), 4, BigDecimal.ROUND_UP));
                if (slopeDensity.compareTo(BigDecimal.ONE)>0){
                    slopeDensity=BigDecimal.ONE;
                }
                teraData.setSlopeDensity(slopeDensity);
                teraData.setGeomText((String) objects1[0]);
            }else {
                teraData.setSlopeArea(BigDecimal.ZERO);
                teraData.setSlopeDensity(BigDecimal.ZERO);
                teraData.setGeomText((String) entity.get("smgeometry"));
            }
            teraData.setDspId(dzzhSlideParam.getId());
            lawAnalysisRepository.save4(teraData);
        }
        //删除中间表----------谨慎操作
        if (PlatformObjectUtils.isNotEmpty(resultLayerName4)) {
            lawAnalysisRepository.dropTable(resultLayerName4);
        }
        return RestResponse.succeed("计算成功!");
    }

    public RestResponse count41(CountParam param1) {
        delete(4);
        // JSONObject valueMap = new JSONObject();
        // valueMap.put("versionCode", param1.getParam1());
        // valueMap.put("geom", param1.getGeomText());
        // String url = basicDataUrl + "/datacenter/sysDataVersion/queryAllByVersionCode";
        // JSONArray jsonArray = (JSONArray) drillService.getJCSJ(url, 4, valueMap).getData();
        // if (jsonArray == null || jsonArray.size() < 1) {
        //     return RestResponse.fail("该区域没有" + param1.getParam1() + "版本的地形坡度数据");
        // }
        Map<String, List<Map<String, String>>> listMap = eqLandslideService.getDataBySlopeVersion(param1.getGeomText(),
                param1.getParam1());
        List<SlopesVO> slopes1 = new ArrayList<>();
        if (PlatformObjectUtils.isNotEmpty(param1.getParam2())) {
            slopes1 = landslideSiteService.getSlopeAreaByGeomAndVersion1(param1.getGeomText(), param1.getParam2());
        }
        if (PlatformObjectUtils.isNotEmpty(param1.getParam3())) {
            if (slopes1 != null) {
                slopes1.addAll(sensingImageService.getSlopeAreaByGeomAndVersion1(param1.getGeomText(), param1.getParam3()));
            } else {
                slopes1 = sensingImageService.getSlopeAreaByGeomAndVersion1(param1.getGeomText(), param1.getParam3());
            }
        }
        Map<Integer, JSONArray> map1 = new HashMap<>();
        JSONArray jsonArray = null;
        BigDecimal slope;//地形坡度
        Integer key1 = 0;
        for (Map.Entry<String, List<Map<String, String>>> listEntry : listMap.entrySet()) {
            slope = new BigDecimal(listEntry.getKey());
            if (slope.compareTo(BigDecimal.valueOf(15)) < 0) {//<15
                key1 = 1;
            } else if (slope.compareTo(BigDecimal.valueOf(15)) > -1 && slope.compareTo(BigDecimal.valueOf(25)) < 0) {//15~25
                key1 = 2;
            } else if (slope.compareTo(BigDecimal.valueOf(25)) > -1 && slope.compareTo(BigDecimal.valueOf(35)) < 0) {//25~35
                key1 = 3;
            } else if (slope.compareTo(BigDecimal.valueOf(35)) > -1 && slope.compareTo(BigDecimal.valueOf(45)) < 0) {//35~45
                key1 = 4;
            } else if (slope.compareTo(BigDecimal.valueOf(45)) > -1 && slope.compareTo(BigDecimal.valueOf(55)) < 0) {//45~55
                key1 = 5;
            } else if (slope.compareTo(BigDecimal.valueOf(55)) > 0) {//>55
                key1 = 6;
            }
            if (map1.containsKey(key1)) {
                jsonArray = map1.get(key1);
            } else {
                jsonArray = new JSONArray();
            }
            jsonArray.addAll(JSON.parseArray(JSON.toJSONString(listEntry.getValue())));
            map1.put(key1, jsonArray);
        }
        /*Iterator<Map.Entry<String, List<Map<String, String>>>> iterator = listMap.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<String, List<Map<String, String>>> next = iterator.next();
            slope = new BigDecimal(next.getKey());
            if (slope.compareTo(BigDecimal.valueOf(44))==0){
                System.out.println("");
            }
            if (slope.compareTo(BigDecimal.valueOf(15)) < 0) {//<15
                key1 = 1;
            } else if (slope.compareTo(BigDecimal.valueOf(15)) > -1 && slope.compareTo(BigDecimal.valueOf(25)) < 0) {//15~25
                key1 = 2;
            } else if (slope.compareTo(BigDecimal.valueOf(25)) > -1 && slope.compareTo(BigDecimal.valueOf(35)) < 0) {//25~35
                key1 = 3;
            } else if (slope.compareTo(BigDecimal.valueOf(35)) > -1 && slope.compareTo(BigDecimal.valueOf(45)) < 0) {//35~45
                key1 = 4;
            } else if (slope.compareTo(BigDecimal.valueOf(45)) > -1 && slope.compareTo(BigDecimal.valueOf(55)) < 0) {//45~55
                key1 = 5;
            } else if (slope.compareTo(BigDecimal.valueOf(55)) > 0) {//>55
                key1 = 6;
            }
            if (map1.containsKey(key1)){
                jsonArray=map1.get(key1);
            }else {
                jsonArray=new JSONArray();
            }
            jsonArray.addAll(JSON.parseArray(JSON.toJSONString(next.getValue())));
            map1.put(key1, jsonArray);
        }*/
        DzzhSlideParam dzzhSlideParam = saveDzzhSlideParam(param1, "4");
        // 1,<15;2,15~25;3,25~35;4,35~45;5,45~55;6,>55
        for (int key = 1; key < 7; key++) {
            Object[] objects1 = null;
            if (map1.get(key) != null) {
                objects1 = getObjects(slopes1, map1.get(key));
            } else {
                continue;
            }
            DzzhSlideResultSlope teraData = new DzzhSlideResultSlope();
            teraData.setDsrsId(UUIDGenerator.getUUID());
            teraData.setSlopeRange(String.valueOf(key));
            if (PlatformObjectUtils.isNotEmpty(objects1)) {
                teraData.setSlopeArea((BigDecimal) objects1[2]);
                BigDecimal slopeDensity=objects1[1] == null || new BigDecimal(objects1[1].toString()).compareTo(BigDecimal.ZERO)==0 ? BigDecimal.ZERO : (new BigDecimal(objects1[2]+"")
                        .divide(new BigDecimal(objects1[1]+""), 4, BigDecimal.ROUND_UP));
                if (slopeDensity.compareTo(BigDecimal.ONE)>0){
                    slopeDensity=BigDecimal.ONE;
                }
                teraData.setSlopeDensity(slopeDensity);
                teraData.setGeomText((String) objects1[0]);
            }
            teraData.setDspId(dzzhSlideParam.getId());
            // teraData.setSlopeVersion(param1.getParam1());
            // teraData.setLandsSiteVersion(param1.getParam2());
            // teraData.setSensingImgVersion(param1.getParam3());
            lawAnalysisRepository.save4(teraData);
        }
        return RestResponse.succeed("计算成功!");
    }

    /**
     * 坡向
     * @param param1
     * @return
     */
    @Override
    public RestResponse count5(CountParam param1) {
        delete(5);
        String resultLayerName1 = this.getDataBySlopeVersion(param1.getGeomText(), param1.getParam1());
        if (PlatformObjectUtils.isEmpty(resultLayerName1)){
//            return RestResponse.fail("未获取到"+param1.getParam1()+"版本的坡向文件！");
            return RestResponse.fail("任务范围内不包含"+param1.getParam1()+"版本的坡向文件数据！");
        }

        String countString1 = "Con([dzzhTifCount." + resultLayerName1 + "]<0,-9999,Con([dzzhTifCount." + resultLayerName1 + "]==0,1," +
                "Con([dzzhTifCount." + resultLayerName1 + "]<90,2,Con([dzzhTifCount." + resultLayerName1 + "]==90,3," +
                "Con([dzzhTifCount." + resultLayerName1 + "]<180,4,Con([dzzhTifCount." + resultLayerName1 + "]==180,5," +
                "Con([dzzhTifCount." + resultLayerName1 + "]<270,6,Con([dzzhTifCount." + resultLayerName1 + "]==270,7," +
                "Con([dzzhTifCount." + resultLayerName1 + "]<360,8,-9999)))))))))";
        String resultLayerName2 = "dzzh分布规律分析_坡向计算_" + System.currentTimeMillis();//裁剪计算结果数据集

        RestResponse restResponse4 = countTif(countString1, resultLayerName2);
        if (restResponse4.getCode() != 200) {
            return restResponse4;
        }
        String resultLayerName3 = "dzzh_坡向_矢量化结果数据集" + System.currentTimeMillis();
        String resultLayerName4 = "dzzh_slide_aspect_values"+BigDecimal.valueOf(Math.random()*1000000).intValue()+BigDecimal.valueOf(Math.random()*10000).intValue();
        Map<String, Object> map2_1 = new HashMap<>();
        map2_1.put("type", "gridFusion");
        map2_1.put("layerName", resultLayerName2);
        map2_1.put("resultLayerName1", resultLayerName3);
        map2_1.put("resultLayerName2", resultLayerName4);
        // map2_1.put("mapsName", mapsName);//图层名称
        RestResponse serverToken = hypergraphService.getServerToken(map2_1);
        if (serverToken.getCode() != 200) {
            return serverToken;
        }

        List<Map<String, Object>> slopes1 = new ArrayList<>();
        if (PlatformObjectUtils.isNotEmpty(param1.getParam2())) {
            slopes1 = landslideSiteService.getByGeomAndVersion2(resultLayerName4, param1.getParam2());
        }
        if (PlatformObjectUtils.isNotEmpty(param1.getParam3())) {
            if (slopes1 != null) {
                slopes1.addAll(sensingImageService.getByGeomAndVersion2(resultLayerName4, param1.getParam3()));
            } else {
                slopes1 = sensingImageService.getByGeomAndVersion2(resultLayerName4, param1.getParam3());
            }
        }

        Map<Integer, Object[]> map1 = new HashMap<>();
        Object[] objects=null;
        for (Map<String, Object> slope:slopes1){
            // b.gridvalue gridvalue,b.smarea smarea,sum(a.landslide_area) sum,st_AsText(b.smgeometry) smgeometry
            Integer key=Double.valueOf(slope.get("gridvalue")+"").intValue();
            if (map1.containsKey(key)){
                objects=map1.get(key);
                objects[1] = new BigDecimal(objects[1]+"").add(new BigDecimal(slope.get("smarea")+""));
            }else {
                objects = new Object[3];
                objects[0] = slope.get("smgeometry");//坡度与区域相交部分的空间数据
                objects[1] = slope.get("smarea");//坡度的面积
                objects[2] = slope.get("sum");//滑坡面积
            }
            map1.put(key,objects);
        }
        DzzhSlideParam dzzhSlideParam = saveDzzhSlideParam(param1, "5");
        // 1,N;2,NE;3,E;4,ES;5,S;6,SW;7,W;8,WN
        List<Map<String, Object>> mapList = lawAnalysisRepository.getByTableName(resultLayerName4);
        for (Map<String, Object> entity :mapList) {
            //gridvalue,st_asText(smgeometry) smgeometry
            Integer key = Double.valueOf(entity.get("gridvalue")+"").intValue();
            Object[] objects1 = map1.get(key);
            DzzhSlideResultAspect aspectData = new DzzhSlideResultAspect();
            aspectData.setDsraId(UUIDGenerator.getUUID());
            aspectData.setAspectRange(String.valueOf(key));
            if (PlatformObjectUtils.isNotEmpty(objects1)) {
                aspectData.setSlopeArea(new BigDecimal(objects1[2]+"").divide(BigDecimal.valueOf(1000000), 4, BigDecimal.ROUND_UP));
                BigDecimal slopeDensity=objects1[1] == null || new BigDecimal(objects1[1].toString()).compareTo(BigDecimal.ZERO)==0? BigDecimal.ZERO : (new BigDecimal(objects1[2]+"")
                        .divide(new BigDecimal(objects1[1]+""), 4, BigDecimal.ROUND_UP));
                if (slopeDensity.compareTo(BigDecimal.ONE)>0){
                    slopeDensity=BigDecimal.ONE;
                }
                aspectData.setSlopeDensity(slopeDensity);
                aspectData.setGeomText((String) objects1[0]);
            }else {
                aspectData.setSlopeArea(BigDecimal.ZERO);
                aspectData.setSlopeDensity(BigDecimal.ZERO);
                aspectData.setGeomText((String) entity.get("smgeometry"));
            }
            aspectData.setDspId(dzzhSlideParam.getId());
            lawAnalysisRepository.save5(aspectData);
        }
        //删除中间表----------谨慎操作
        if (PlatformObjectUtils.isNotEmpty(resultLayerName4)) {
            lawAnalysisRepository.dropTable(resultLayerName4);
        }
        return RestResponse.succeed("计算成功!");
    }

    public RestResponse count51(CountParam param1) {
        delete(5);
        // JSONObject valueMap = new JSONObject();
        // valueMap.put("versionCode", param1.getParam1());
        // valueMap.put("geom", param1.getGeomText());
        // String url = basicDataUrl + "/datacenter/sysDataVersion/queryAllByVersionCode";
        // JSONArray jsonArray = (JSONArray) drillService.getJCSJ(url, 4, valueMap).getData();
        // if (jsonArray == null || jsonArray.size() < 1) {
        //     return RestResponse.fail("该区域没有" + param1.getParam1() + "版本的坡向数据");
        // }
        Map<String, List<Map<String, String>>> listMap = eqLandslideService.getDataBySlopeVersion(param1.getGeomText(),
                param1.getParam1());
        // List<String> list = this.getDataBySlopeVersion(param1.getGeomText(), param1.getParam1());

        List<SlopesVO> slopes1 = new ArrayList<>();
        if (PlatformObjectUtils.isNotEmpty(param1.getParam2())) {
            slopes1 = landslideSiteService.getSlopeAreaByGeomAndVersion1(param1.getGeomText(), param1.getParam2());
        }
        if (PlatformObjectUtils.isNotEmpty(param1.getParam3())) {
            if (slopes1 != null) {
                slopes1.addAll(sensingImageService.getSlopeAreaByGeomAndVersion1(param1.getGeomText(), param1.getParam3()));
            } else {
                slopes1 = sensingImageService.getSlopeAreaByGeomAndVersion1(param1.getGeomText(), param1.getParam3());
            }
        }
        Map<Integer, JSONArray> map1 = new HashMap<>();
        String aspect;
        int key1 = 0;
        for (Map.Entry<String, List<Map<String, String>>> listEntry : listMap.entrySet()) {
            aspect = listEntry.getKey();//坡向
            if (aspect.equals("N")) {
                key1 = 1;
            } else if (aspect.equals("NE")) {
                key1 = 2;
            } else if (aspect.equals("E")) {
                key1 = 3;
            } else if (aspect.equals("ES")) {
                key1 = 4;
            } else if (aspect.equals("S")) {
                key1 = 5;
            } else if (aspect.equals("SW")) {
                key1 = 6;
            } else if (aspect.equals("W")) {
                key1 = 7;
            } else if (aspect.equals("WN")) {
                key1 = 8;
            }
            map1.put(key1, JSON.parseArray(JSON.toJSONString(listEntry.getValue())));
        }
        DzzhSlideParam dzzhSlideParam = saveDzzhSlideParam(param1, "5");
        // 1,N;2,NE;3,E;4,ES;5,S;6,SW;7,W;8,WN
        for (int key = 1; key < 9; key++) {
            Object[] objects1 = null;
            if (map1.get(key) != null) {
                objects1 = getObjects(slopes1, map1.get(key));
            } else {
                continue;
            }
            DzzhSlideResultAspect aspectData = new DzzhSlideResultAspect();
            aspectData.setDsraId(UUIDGenerator.getUUID());
            aspectData.setAspectRange(String.valueOf(key));
            if (PlatformObjectUtils.isNotEmpty(objects1)) {
                aspectData.setSlopeArea((BigDecimal) objects1[2]);
                BigDecimal slopeDensity=objects1[1] == null || new BigDecimal(objects1[1].toString()).compareTo(BigDecimal.ZERO)==0? BigDecimal.ZERO : (new BigDecimal(objects1[2]+"")
                        .divide(new BigDecimal(objects1[1]+""), 4, BigDecimal.ROUND_UP));
                if (slopeDensity.compareTo(BigDecimal.ONE)>0){
                    slopeDensity=BigDecimal.ONE;
                }
                aspectData.setSlopeDensity(slopeDensity);
                aspectData.setGeomText((String) objects1[0]);
            }
            aspectData.setDspId(dzzhSlideParam.getId());
            // aspectData.setAspectVersion(param1.getParam1());
            // aspectData.setLandsSiteVersion(param1.getParam2());
            // aspectData.setSensingImgVersion(param1.getParam3());
            lawAnalysisRepository.save5(aspectData);
        }
        return RestResponse.succeed("计算成功!");
    }

    @Override
    public RestResponse count6(CountParam param1) {
        delete(6);

//        String url = basicDataUrl + "/datacenter/jcHydl/findAll?geom=" + param1.getGeomText();
//        JSONArray jsonArray = (JSONArray) drillService.getJCSJ(url, 3).getData();

        //生成缓冲区（2公里）
        String bufferGeomText = lawAnalysisRepository.getBufferByGeomMeter(param1.getGeomText(), 2 * 1000);
        JSONObject valueMap = new JSONObject();
        valueMap.put("geom", bufferGeomText);
        String url = basicDataUrl + "/datacenter/jcHydl/findAllUnion";
        JSONArray jsonArray = (JSONArray) drillService.getJCSJ(url, 4, valueMap).getData();

        if (jsonArray == null || jsonArray.size() < 1) {
            return RestResponse.fail("该区域没有水系数据");
        }

        DzzhSlideParam dzzhSlideParam = saveDzzhSlideParam(param1, "6");
        List<String> list = new ArrayList<>();
        //区域面积（度)
        BigDecimal areaDegree = lawAnalysisRepository.getAreaDegreeByGeom(param1.getGeomText());
        //区域总面积（平方公里)
//        BigDecimal areaTransform = lawAnalysisRepository.getAreaByGeom(param1.getGeomText());
        //根据区域投影到6度带或3度带，计算投影面积之和（平方公里)
        BigDecimal areaTransform = elevationMapService.getAreaByGeomEpsgCount(param1.getGeomText());
        //获取全部水系线空间数据
        JSONObject jsonObject = null;
        String geomText = "";//全部水系线空间数据
        for (int i = 0; i < jsonArray.size(); i++) {
            jsonObject = jsonArray.getJSONObject(i);
            String lineGeomText = jsonObject.getString("geom");
            if (PlatformObjectUtils.isNotEmpty(geomText)) {
                geomText = lawAnalysisRepository.getStUnion(geomText, lineGeomText);
            } else {
                geomText = lineGeomText;
            }
        }
        //水系。1,0-500;2,500-1000;3,1000-1500;4,1500-2000;5,>2000
        for (int key = 1; key < 6; key++) {
            List<SlopesVO> slopes1 = null;
            //水系缓冲区的面积和空间数据
            /*BufferAreaVO objects = lawAnalysisRepository.getBufferByGeom(param1.getGeomText(), geomText,
                    key * 500, (key - 1) * 500);*/
            //区域的缓冲区内水系数据按距离分段生成缓冲区环
            BufferAreaVO objects = lawAnalysisRepository.getBufferByGeomBuffer(bufferGeomText, param1.getGeomText(), geomText,
                    key * 500, (key - 1) * 500);
            if (objects == null || objects.getGeom() == null || objects.getGeom().equals("POLYGON EMPTY")) {
                continue;
            }
            //计算滑坡面积
            BigDecimal slopeArea = BigDecimal.ZERO;
            if (PlatformObjectUtils.isNotEmpty(param1.getParam2())) {
                slopes1 = landslideSiteService.getSlopeAreaByGeomAndVersion1(objects.getGeom(), param1.getParam2());
            }
            if (PlatformObjectUtils.isNotEmpty(param1.getParam3())) {
                if (slopes1 != null) {
                    slopes1.addAll(sensingImageService.getSlopeAreaByGeomAndVersion1(objects.getGeom(), param1.getParam3()));
                } else {
                    slopes1 = sensingImageService.getSlopeAreaByGeomAndVersion1(objects.getGeom(), param1.getParam3());
                }
            }
            if (slopes1 != null) {
                for (SlopesVO fileData : slopes1) {
                    if (!list.contains((String) fileData.getId())) {
                        list.add((String) fileData.getId());
                        slopeArea = slopeArea.add((BigDecimal) fileData.getLandslideArea());
                    }
                }
                slopes1.clear();
            }

            //根据面积（度）与区域总面积（度）的比例和区域投影总面积（平方公里）获取投影面积
            BigDecimal area = objects.getArea().divide(areaDegree, 6, BigDecimal.ROUND_HALF_UP).multiply(areaTransform);
            objects.setArea(area);
            Object[] objects2 = new Object[3];
            objects2[0] = objects.getGeom();//与区域相交部分的空间数据
            objects2[1] = objects.getArea();//面积（平方公里）
            objects2[2] = slopeArea;//滑坡面积（平方公里）
            DzzhSlideResultDrainage aspectData = new DzzhSlideResultDrainage();
            aspectData.setDsrdId(UUIDGenerator.getUUID());
            aspectData.setDrainageRange(String.valueOf(key));
            if (PlatformObjectUtils.isNotEmpty(objects2)) {
                aspectData.setSlopeArea(new BigDecimal(objects2[2]+"").divide(BigDecimal.valueOf(1000000), 4, BigDecimal.ROUND_UP));
                BigDecimal slopeDensity=objects2[1] == null || new BigDecimal(objects2[1].toString()).compareTo(BigDecimal.ZERO)==0 ? BigDecimal.ZERO : (new BigDecimal(objects2[2]+"")
                        .divide(new BigDecimal(objects2[1]+""), 4, BigDecimal.ROUND_UP));
                if (slopeDensity.compareTo(BigDecimal.ONE)>0){
                    slopeDensity=BigDecimal.ONE;
                }
                aspectData.setSlopeDensity(slopeDensity);
                aspectData.setGeomText((String) objects2[0]);
            }
            aspectData.setDspId(dzzhSlideParam.getId());
            // aspectData.setDrainageVersion(param1.getParam1());
            // aspectData.setLandsSiteVersion(param1.getParam2());
            // aspectData.setSensingImgVersion(param1.getParam3());
            lawAnalysisRepository.save6(aspectData);

            list.clear();
        }

        return RestResponse.succeed("计算成功!");
    }

    /*@Override
    public RestResponse count6(CountParam param1) {
        delete(6);
        Map<Integer, Object[]> map = new HashMap<>();
        String url = basicDataUrl + "/datacenter/jcHydl/findAll?geom=" + param1.getGeomText();
        JSONArray jsonArray = (JSONArray) drillService.getJCSJ(url, 3).getData();
        if (jsonArray.size() < 1) {
            return RestResponse.fail("该区域没有水系数据");
        }

        DzzhSlideParam dzzhSlideParam = saveDzzhSlideParam(param1, "6");
        List<String> list = new ArrayList<>();
        //水系。1,0-500;2,500-1000;3,1000-1500;4,1500-2000;5,>2000
        for (int key = 1; key < 6; key++) {
            JSONObject jsonObject = null;
            // String geomText = null;//水系与区域相交部分的空间数据
            // BigDecimal areaByGeom = BigDecimal.ZERO;//水系的面积

            List<SlopesVO> slopes1 = null;
            for (int i = 0; i < jsonArray.size(); i++) {
                jsonObject = jsonArray.getJSONObject(i);
                String geomText = jsonObject.getString("geom");

                BigDecimal slopeArea = BigDecimal.ZERO;
                if (PlatformObjectUtils.isNotEmpty(param1.getParam2())) {
                    slopes1 = landslideSiteService.getSlopeAreaByGeomAndVersion1(param1.getGeomText(), geomText, key * 500,
                            (key - 1) * 500, param1.getParam2());
                }
                if (PlatformObjectUtils.isNotEmpty(param1.getParam3())) {
                    if (slopes1 != null) {
                        slopes1.addAll(sensingImageService.getSlopeAreaByGeomAndVersion1(param1.getGeomText(), geomText,
                                key * 500, (key - 1) * 500, param1.getParam3()));
                    } else {
                        slopes1 = sensingImageService.getSlopeAreaByGeomAndVersion1(param1.getGeomText(), geomText, key * 500,
                                (key - 1) * 500, param1.getParam3());
                    }
                }

                if (slopes1 != null) {
                    for (SlopesVO fileData : slopes1) {
                        if (!list.contains((String) fileData.getId())) {
                            list.add((String) fileData.getId());
                            slopeArea = slopeArea.add((BigDecimal) fileData.getLandslideArea());
                        }
                    }
                    //断层缓冲区的面积和空间数据
                    BufferAreaVO objects = lawAnalysisRepository.getBufferByGeom(param1.getGeomText(), geomText,
                            key * 500,(key - 1) * 500);
                    if (objects != null) {
                        Object[] objects2 = null;
                        if (map.containsKey(key)) {
                            objects2 = map.get(key);
                            objects2[0] = lawAnalysisRepository.getStUnion(objects.getGeom(), objects2[0]);
                            objects2[1] = ((BigDecimal) objects2[1]).add((BigDecimal) objects.getArea());
                            // objects2[2] = ((BigDecimal) objects2[2]).add(slopeArea);
                        } else {
                            objects2 = new Object[3];
                            objects2[0] = objects.getGeom();//高程与区域相交部分的空间数据
                            objects2[1] = objects.getArea();//高程的面积
                            objects2[2] = slopeArea;//滑坡面积
                            map.put(key, objects2);
                        }
                    }
                    slopes1.clear();
                }
            }

            list.clear();
        }

        for (Integer key2 : map.keySet()) {
            Object[] objects1 = map.get(key2);
            DzzhSlideResultDrainage aspectData = new DzzhSlideResultDrainage();
            aspectData.setDsrdId(UUIDGenerator.getUUID());
            aspectData.setDrainageRange(String.valueOf(key2));
            if (PlatformObjectUtils.isNotEmpty(objects1)) {
                aspectData.setSlopeArea((BigDecimal) objects1[2]);
                aspectData.setSlopeDensity(objects1[1]==null?BigDecimal.ZERO:((BigDecimal) objects1[2])
                        .divide((BigDecimal) objects1[1], 1, BigDecimal.ROUND_UP));
                aspectData.setGeomText((String) objects1[0]);
            }
            aspectData.setDspId(dzzhSlideParam.getId());
            // aspectData.setDrainageVersion(param1.getParam1());
            // aspectData.setLandsSiteVersion(param1.getParam2());
            // aspectData.setSensingImgVersion(param1.getParam3());
            lawAnalysisRepository.save6(aspectData);
        }
        return RestResponse.succeed("计算成功!");
    }*/

    @Override
    public RestResponse count7(CountParam param1) {
        delete(7);
        Map<Integer, Object[]> map = new HashMap<>();
        JSONObject valueMap = new JSONObject();
        valueMap.put("versionCode", param1.getParam1());
        valueMap.put("geom", param1.getGeomText());
        String url = basicDataUrl + "/datacenter/sysDataVersion/queryAllByVersionCode";
        //        JSONArray jsonArray = (JSONArray) drillService.getJCSJ(url, 4,valueMap).getData();
        JSONObject jsonObject = (JSONObject) drillService.getJCSJ(url, 1, valueMap).getData();
        JSONArray jsonArray = jsonObject.getJSONArray("data");
        if (jsonArray == null || jsonArray.size() < 1) {
            return RestResponse.fail("该区域没有" + param1.getParam1() + "版本的地层岩性数据");
        }
        List<SlopesVO> slopes1 = new ArrayList<>();
        if (PlatformObjectUtils.isNotEmpty(param1.getParam2())) {
            slopes1 = landslideSiteService.getSlopeAreaByGeomAndVersion1(param1.getGeomText(), param1.getParam2());
        }
        if (PlatformObjectUtils.isNotEmpty(param1.getParam3())) {
            if (slopes1 != null) {
                slopes1.addAll(sensingImageService.getSlopeAreaByGeomAndVersion1(param1.getGeomText(), param1.getParam3()));
            } else {
                slopes1 = sensingImageService.getSlopeAreaByGeomAndVersion1(param1.getGeomText(), param1.getParam3());
            }
        }
        Map<String, JSONArray> map1 = new HashMap<>();
        JSONArray jsonArray1 = null;
        JSONObject jsonObject1 = null;
        String lithology;
        for (int j = 0; j < jsonArray.size(); j++) {
            jsonObject1 = jsonArray.getJSONObject(j);
            lithology = jsonObject1.getString("mainCode") + "-" + jsonObject1.getString("mainName") + "-" + jsonObject1.getString("mainSymbol");//地层岩性
            if (map1.containsKey(lithology)) {
                jsonArray1 = map1.get(lithology);
            } else {
                jsonArray1 = new JSONArray();
            }
            jsonArray1.add(jsonObject1);
            map1.put(lithology, jsonArray1);
        }
        DzzhSlideParam dzzhSlideParam = saveDzzhSlideParam(param1, "7");

        for (Map.Entry<String, JSONArray> entry : map1.entrySet()) {
            Object[] objects1 = getObjects(slopes1, entry.getValue());
            DzzhSlideResultLithology lithologyData = new DzzhSlideResultLithology();
            lithologyData.setDsrlId(UUIDGenerator.getUUID());
            String[] split = entry.getKey().split("-");
            lithologyData.setLithologyCode(split[0]);
            lithologyData.setLithologyName(split[1]);
            lithologyData.setLithologyRange(split[2]);

            if (PlatformObjectUtils.isNotEmpty(objects1)) {
                lithologyData.setSlopeArea(new BigDecimal(objects1[2]+"").divide(BigDecimal.valueOf(1000000), 4, BigDecimal.ROUND_UP));
                BigDecimal slopeDensity=objects1[1] == null || new BigDecimal(objects1[1].toString()).compareTo(BigDecimal.ZERO)==0 ? BigDecimal.ZERO : (new BigDecimal(objects1[2]+"")
                        .divide(new BigDecimal(objects1[1]+""), 4, BigDecimal.ROUND_UP));
                if (slopeDensity.compareTo(BigDecimal.ONE)>0){
                    slopeDensity=BigDecimal.ONE;
                }
                lithologyData.setSlopeDensity(slopeDensity);
                lithologyData.setGeomText((String) objects1[0]);
            }
            lithologyData.setDspId(dzzhSlideParam.getId());
            // lithologyData.setLithologyVersion(param1.getParam1());
            // lithologyData.setLandsSiteVersion(param1.getParam2());
            // lithologyData.setSensingImgVersion(param1.getParam3());
            lawAnalysisRepository.save7(lithologyData);
        }
        return RestResponse.succeed("计算成功!");
    }

    private Object[] getObjects(List<SlopesVO> slopes, JSONArray jsonArray) {
        Object[] objects = null;
        for (int i = 0; i < jsonArray.size(); i++) {
            String geomText = jsonArray.getJSONObject(i).getString("geom");//空间数据
//            BigDecimal areaByGeom = lawAnalysisRepository.getAreaByGeom(geomText);
            //根据区域投影到6度带或3度带，计算投影面积之和（平方公里)
            BigDecimal areaByGeom = elevationMapService.getAreaByGeomEpsgCount(geomText);
            if (PlatformObjectUtils.isNotEmpty(objects)) {
                objects[0] = lawAnalysisRepository.getStUnion(objects[0], geomText);
                objects[1] = areaByGeom.add((BigDecimal) objects[1]);
            } else {
                objects = new Object[3];
                objects[0] = geomText;//坡度与区域相交部分的空间数据
                objects[1] = areaByGeom;//坡度的面积
                objects[2] = BigDecimal.ZERO;//滑坡面积
            }
            for (SlopesVO data : slopes) {
                // Boolean stIntersects = lawAnalysisRepository.getSTIntersects(geomText, data.getLongitude(), data.getLatitude());
                if (lawAnalysisRepository.getSTIntersects(geomText, (BigDecimal) data.getLongitude(), (BigDecimal) data.getLatitude())) {
                    objects[2] = ((BigDecimal) data.getLandslideArea()).add((BigDecimal) objects[2]);
                }
            }
        }
        return objects;
    }

    void delete(int tab) {
        String userId = PlatformSessionUtils.getUserId();
        DzzhSlideParam dzzhSlideParam = lawAnalysisRepository.getDzzhSlideParamByUserId(userId, String.valueOf(tab));
        lawAnalysisRepository.delete0(userId, String.valueOf(tab));
        if (dzzhSlideParam != null) {
            switch (tab) {
                case 1:
                    lawAnalysisRepository.delete1(dzzhSlideParam.getId());
                    break;
                case 2:
                    lawAnalysisRepository.delete2(dzzhSlideParam.getId());
                    break;
                case 3:
                    lawAnalysisRepository.delete3(dzzhSlideParam.getId());
                    break;
                case 4:
                    lawAnalysisRepository.delete4(dzzhSlideParam.getId());
                    break;
                case 5:
                    lawAnalysisRepository.delete5(dzzhSlideParam.getId());
                    break;
                case 6:
                    lawAnalysisRepository.delete6(dzzhSlideParam.getId());
                    break;
                case 7:
                    lawAnalysisRepository.delete7(dzzhSlideParam.getId());
                    break;
            }
        }
    }

    DzzhSlideParam saveDzzhSlideParam(CountParam param1, String paramType) {
        DzzhSlideParam dzzhSlideParam = new DzzhSlideParam();
        dzzhSlideParam.setId(UUIDGenerator.getUUID());
        dzzhSlideParam.setParam1(param1.getParam1());
        dzzhSlideParam.setParam2(param1.getParam2());
        dzzhSlideParam.setParam3(param1.getParam3());
        dzzhSlideParam.setTab(param1.getTab1());
        dzzhSlideParam.setParamType(paramType);
        dzzhSlideParam.setGeom(param1.getGeomText());
        dzzhSlideParam.setUserId(PlatformSessionUtils.getUserId());
        lawAnalysisRepository.save0(dzzhSlideParam);
        return dzzhSlideParam;
    }

    public String getDataBySlopeVersion(String geom, String version) {
        SysDataVersion sysDataVersion = sysDataVersionRepository.getByVersionCode(version);
        AttachmentInfoEntity attach = attachmentInfoService.getAttach(sysDataVersion.getDataFileIds());
        String resultLayerName1 = elevationMapService.getByGeomAndTIF(geom, attach.getAttachPath());
        return resultLayerName1;
    }

    private RestResponse countTif(String countString, String resultLayerName) {
        //栅格计算
        Map<String, Object> map2_1 = new HashMap<>();
        map2_1.put("type", "countTif2");
        map2_1.put("layerName", resultLayerName);
        map2_1.put("countString", countString);
        // map2_1.put("mapsName", mapsName);//图层名称
        return hypergraphService.getServerToken(map2_1);
    }

    @Override
    public RestResponse getDataByType(String tab) {
        JSONObject jsonObject = new JSONObject();
        String userId = PlatformSessionUtils.getUserId();
        DzzhSlideParam dzzhSlideParam = lawAnalysisRepository.getDzzhSlideParamByUserId(userId, tab);
        jsonObject.put("dzzhSlideParam", dzzhSlideParam);
        if (dzzhSlideParam != null) {
            switch (tab) {
                case "1":
                    jsonObject.put("byDspId", lawAnalysisRepository.getByDspId1(dzzhSlideParam.getId()));
                    break;
                case "2":
                    jsonObject.put("byDspId", lawAnalysisRepository.getByDspId2(dzzhSlideParam.getId()));
                    break;
                case "3":
                    jsonObject.put("byDspId", lawAnalysisRepository.getByDspId3(dzzhSlideParam.getId()));
                    break;
                case "4":
                    jsonObject.put("byDspId", lawAnalysisRepository.getByDspId4(dzzhSlideParam.getId()));
                    break;
                case "5":
                    jsonObject.put("byDspId", lawAnalysisRepository.getByDspId5(dzzhSlideParam.getId()));
                    break;
                case "6":
                    jsonObject.put("byDspId", lawAnalysisRepository.getByDspId6(dzzhSlideParam.getId()));
                    break;
                case "7":
                    jsonObject.put("byDspId", lawAnalysisRepository.getByDspId7(dzzhSlideParam.getId()));
                    break;
            }
        }

        return RestResponse.succeed(jsonObject);
    }

    @Override
    public void exportByDspIdAndType(HttpServletResponse response, String dspId, String type) {
        try {
            switch (type) {
                case "1":
                    List<DzzhSlideResultIntensity> byDspId1 = lawAnalysisRepository.getByDspId1(dspId);
                    for (DzzhSlideResultIntensity entity : byDspId1) {
                        String intensity = "";
                        switch (entity.getIntensity()) {
                            case "5":
                                intensity = "V";
                                break;
                            case "6":
                                intensity = "VI";
                                break;
                            case "7":
                                intensity = "VII";
                                break;
                            case "8":
                                intensity = "VIII";
                                break;
                            case "9":
                                intensity = "IX";
                                break;
                            case "10":
                                intensity = "X";
                                break;
                            case "11":
                                intensity = "XI";
                                break;
                            case "12":
                                intensity = "XII";
                                break;
                        }
                        entity.setIntensity(intensity);
                    }
                    EasyPoiExcelUtil.exportExcel(byDspId1, null, "sheet", DzzhSlideResultIntensity.class, "与地震烈度关系的结果导出.xlsx",
                            response);
                    break;
                case "2":
                    List<DzzhSlideResultFault> byDspId2 = lawAnalysisRepository.getByDspId2(dspId);
                    for (DzzhSlideResultFault entity : byDspId2) {
                        //7,>30;6,25~30;5,20~25;4,15~20;3,10~15;2,5~10;1,0~5
                        String param = "";
                        switch (entity.getFaultRange()) {
                            case "1":
                                param = "0~5";
                                break;
                            case "2":
                                param = "5~10";
                                break;
                            case "3":
                                param = "0~15";
                                break;
                            case "4":
                                param = "15~20";
                                break;
                            case "5":
                                param = "20~25";
                                break;
                            case "6":
                                param = "25~30";
                                break;
                            case "7":
                                param = ">30";
                                break;
                        }
                        entity.setFaultRange(param);
                    }
                    // ExportParams params = new ExportParams();
                    // params.setSheetName("sheet");
                    // params.setType(ExcelType.XSSF);
                    // params.setHeight((short) 8);
                    // FileUtil.exportExcel(byDspId2, DzzhSlideResultFault.class, "与距断层的距离关系的结果导出.xlsx", params, response);
                    EasyPoiExcelUtil.exportExcel(byDspId2, null, "sheet", DzzhSlideResultFault.class, "与距断层的距离关系的结果导出.xlsx",
                            response);
                    break;
                case "3":
                    List<DzzhSlideResultTera> byDspId3 = lawAnalysisRepository.getByDspId3(dspId);
                    for (DzzhSlideResultTera entity : byDspId3) {
                        //1,<0.6;2,0.6~1;3,1~1.5;4,1.5~2;5,2~2.5;6,2.5~3;7,3~3.5;8,>3.5
                        String param = "";
                        switch (entity.getTeraRange()) {
                            case "1":
                                param = "<0.6";
                                break;
                            case "2":
                                param = "0.6~1";
                                break;
                            case "3":
                                param = "1~1.5";
                                break;
                            case "4":
                                param = "1.5~2";
                                break;
                            case "5":
                                param = "2.5~3";
                                break;
                            case "6":
                                param = "3~3.5";
                                break;
                            case "7":
                                param = ">3.5";
                                break;
                        }
                        entity.setTeraRange(param);
                    }
                    EasyPoiExcelUtil.exportExcel(byDspId3, null, "sheet", DzzhSlideResultTera.class, "与高程关系的结果导出.xlsx",
                            response);
                    break;
                case "4":
                    List<DzzhSlideResultSlope> byDspId4 = lawAnalysisRepository.getByDspId4(dspId);
                    for (DzzhSlideResultSlope entity : byDspId4) {
                        //1,<15;2,15~25;3,25~35;4,35~45;5,45~55;6,>55
                        String param = "";
                        switch (entity.getSlopeRange()) {
                            case "1":
                                param = "<15";
                                break;
                            case "2":
                                param = "15~25";
                                break;
                            case "3":
                                param = "25~35";
                                break;
                            case "4":
                                param = "35~45";
                                break;
                            case "5":
                                param = "2.5~3";
                                break;
                            case "6":
                                param = "45~55";
                                break;
                            case "7":
                                param = ">55";
                                break;
                        }
                        entity.setSlopeRange(param);
                    }
                    EasyPoiExcelUtil.exportExcel(byDspId4, null, "sheet", DzzhSlideResultSlope.class, "与地形坡度关系的结果导出.xlsx",
                            response);
                    break;
                case "5":
                    List<DzzhSlideResultAspect> byDspId5 = lawAnalysisRepository.getByDspId5(dspId);
                    for (DzzhSlideResultAspect entity : byDspId5) {
                        // 1,N;2,NE;3,E;4,ES;5,S;6,SW;7,W;8,WN
                        String param = "";
                        switch (entity.getAspectRange()) {
                            case "1":
                                param = "N";
                                break;
                            case "2":
                                param = "NE";
                                break;
                            case "3":
                                param = "E";
                                break;
                            case "4":
                                param = "ES";
                                break;
                            case "5":
                                param = "S";
                                break;
                            case "6":
                                param = "SW";
                                break;
                            case "7":
                                param = "W";
                                break;
                            case "8":
                                param = "WN";
                                break;
                        }
                        entity.setAspectRange(param);
                    }
                    EasyPoiExcelUtil.exportExcel(byDspId5, null, "sheet", DzzhSlideResultAspect.class, "与坡向关系的结果导出.xlsx",
                            response);
                    break;
                case "6":
                    List<DzzhSlideResultDrainage> byDspId6 = lawAnalysisRepository.getByDspId6(dspId);
                    for (DzzhSlideResultDrainage entity : byDspId6) {
                        //1,0-500;2,500-1000;3,1000-1500;4,1500-2000;5,>2000
                        String param = "";
                        switch (entity.getDrainageRange()) {
                            case "1":
                                param = "0-500";
                                break;
                            case "2":
                                param = "500-1000";
                                break;
                            case "3":
                                param = "1000-1500";
                                break;
                            case "4":
                                param = "1500-2000";
                                break;
                            case "5":
                                param = ">2000";
                                break;
                        }
                        entity.setDrainageRange(param);
                    }
                    EasyPoiExcelUtil.exportExcel(byDspId6, null, "sheet", DzzhSlideResultDrainage.class, "与水系关系的结果导出.xlsx",
                            response);
                    break;
                case "7":
                    List<DzzhSlideResultLithology> byDspId7 = lawAnalysisRepository.getByDspId7(dspId);
                    for (DzzhSlideResultLithology entity : byDspId7) {
                        // 1,Q4;2,Er;3,T3z;4,T3zh;5,T2zg;6,T1b;7,Tγo;8,P2b-d;9,Psd-d;10,C2h;11,Cz-h;12,D2y
                        String param = "";
                        switch (entity.getLithologyRange()) {
                            case "1":
                                param = "Q4";
                                break;
                            case "2":
                                param = "Er";
                                break;
                            case "3":
                                param = "T3z";
                                break;
                            case "4":
                                param = "T3zh";
                                break;
                            case "5":
                                param = "T2zg";
                                break;
                            case "6":
                                param = "T1b";
                                break;
                            case "7":
                                param = "Tγo";
                                break;
                            case "8":
                                param = "P2b-d";
                                break;
                            case "9":
                                param = "Psd-d";
                                break;
                            case "10":
                                param = "C2h";
                                break;
                            case "11":
                                param = "Cz-h";
                                break;
                            case "12":
                                param = "D2y";
                                break;
                        }
                        entity.setLithologyRange(param);
                        EasyPoiExcelUtil.exportExcel(byDspId7, null, "sheet", DzzhSlideResultLithology.class, "与地层岩性关系的结果导出",
                                response);
                    }
                    EasyPoiExcelUtil.exportExcel(byDspId7, null, "sheet", DzzhSlideResultLithology.class, "与地层岩性关系的结果导出.xlsx",
                            response);
                default:
                    throw new IllegalStateException("Unexpected value: " + type);

            }
            System.out.println("导出成功！");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("导出失败！");
        }
    }
}